package com.employee.servlet;

import com.employee.dao.OptionDao;
import com.employee.entity.Option;
import com.employee.util.JsonResult;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 选项管理Servlet
 */
@WebServlet("/option/*")
public class OptionServlet extends HttpServlet {
    
    private OptionDao optionDao = new OptionDao();
    private Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        PrintWriter out = response.getWriter();
        
        try {
            if ("/list".equals(pathInfo)) {
                // 分页查询
                handleList(request, out);
            } else if ("/detail".equals(pathInfo)) {
                // 查询详情
                handleDetail(request, out);
            } else if ("/category".equals(pathInfo)) {
                // 根据范畴查询（用于下拉框）
                handleByCategory(request, out);
            } else {
                out.print(gson.toJson(JsonResult.error("未知操作")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print(gson.toJson(JsonResult.error("系统错误：" + e.getMessage())));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        PrintWriter out = response.getWriter();
        
        try {
            if ("/add".equals(pathInfo)) {
                // 新增
                handleAdd(request, out);
            } else if ("/update".equals(pathInfo)) {
                // 更新
                handleUpdate(request, out);
            } else if ("/delete".equals(pathInfo)) {
                // 删除
                handleDelete(request, out);
            } else if ("/deleteBatch".equals(pathInfo)) {
                // 批量删除
                handleDeleteBatch(request, out);
            } else {
                out.print(gson.toJson(JsonResult.error("未知操作")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print(gson.toJson(JsonResult.error("系统错误：" + e.getMessage())));
        }
    }
    
    /**
     * 分页查询
     */
    private void handleList(HttpServletRequest request, PrintWriter out) {
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        
        int pageNum = 1;
        int pageSize = 10;
        
        try {
            if (pageNumStr != null && !pageNumStr.isEmpty()) {
                pageNum = Integer.parseInt(pageNumStr);
            }
            if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
                pageSize = Integer.parseInt(pageSizeStr);
            }
        } catch (NumberFormatException e) {
            out.print(gson.toJson(JsonResult.error("页码或页大小格式错误")));
            return;
        }
        
        Map<String, Object> result = optionDao.findByPage(pageNum, pageSize, name, category);
        out.print(gson.toJson(JsonResult.success("查询成功", result)));
    }
    
    /**
     * 查询详情
     */
    private void handleDetail(HttpServletRequest request, PrintWriter out) {
        String id = request.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("ID不能为空")));
            return;
        }
        
        Option option = optionDao.findById(id);
        if (option == null) {
            out.print(gson.toJson(JsonResult.error("选项不存在")));
        } else {
            out.print(gson.toJson(JsonResult.success("查询成功", option)));
        }
    }
    
    /**
     * 根据范畴查询（用于下拉框）
     */
    private void handleByCategory(HttpServletRequest request, PrintWriter out) {
        String category = request.getParameter("category");
        if (category == null || category.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("范畴不能为空")));
            return;
        }
        
        List<Option> options = optionDao.findByCategory(category);
        out.print(gson.toJson(JsonResult.success("查询成功", options)));
    }
    
    /**
     * 新增
     */
    private void handleAdd(HttpServletRequest request, PrintWriter out) {
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        String value = request.getParameter("value");
        String remark = request.getParameter("remark");
        
        // 验证必填项
        if (name == null || name.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("名称不能为空")));
            return;
        }
        if (category == null || category.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("范畴不能为空")));
            return;
        }
        if (value == null || value.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("值不能为空")));
            return;
        }
        
        Option option = new Option();
        option.setName(name.trim());
        option.setCategory(category.trim());
        option.setValue(value.trim());
        option.setRemark(remark != null ? remark.trim() : "");
        
        if (optionDao.insert(option)) {
            out.print(gson.toJson(JsonResult.success("新增成功")));
        } else {
            out.print(gson.toJson(JsonResult.error("新增失败")));
        }
    }
    
    /**
     * 更新
     */
    private void handleUpdate(HttpServletRequest request, PrintWriter out) {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        String value = request.getParameter("value");
        String remark = request.getParameter("remark");
        
        // 验证必填项
        if (id == null || id.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("ID不能为空")));
            return;
        }
        if (name == null || name.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("名称不能为空")));
            return;
        }
        if (category == null || category.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("范畴不能为空")));
            return;
        }
        if (value == null || value.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("值不能为空")));
            return;
        }
        
        Option option = new Option();
        option.setId(id.trim());
        option.setName(name.trim());
        option.setCategory(category.trim());
        option.setValue(value.trim());
        option.setRemark(remark != null ? remark.trim() : "");
        
        if (optionDao.update(option)) {
            out.print(gson.toJson(JsonResult.success("更新成功")));
        } else {
            out.print(gson.toJson(JsonResult.error("更新失败")));
        }
    }
    
    /**
     * 删除
     */
    private void handleDelete(HttpServletRequest request, PrintWriter out) {
        String id = request.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("ID不能为空")));
            return;
        }
        
        if (optionDao.delete(id)) {
            out.print(gson.toJson(JsonResult.success("删除成功")));
        } else {
            out.print(gson.toJson(JsonResult.error("删除失败")));
        }
    }
    
    /**
     * 批量删除
     */
    private void handleDeleteBatch(HttpServletRequest request, PrintWriter out) {
        String idsStr = request.getParameter("ids");
        if (idsStr == null || idsStr.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("请选择要删除的选项")));
            return;
        }
        
        String[] ids = idsStr.split(",");
        if (optionDao.deleteBatch(ids)) {
            out.print(gson.toJson(JsonResult.success("批量删除成功")));
        } else {
            out.print(gson.toJson(JsonResult.error("批量删除失败")));
        }
    }
}
